package com.bluezone.dec.system.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bluezone.dec.common.CacheConstant;
import com.bluezone.dec.common.CodeEnum;
import com.bluezone.dec.common.SystemConstant;
import com.bluezone.dec.configuration.AppConfig;
import com.bluezone.dec.system.service.MonitorAlarmService;
import com.bluezone.dec.system.vo.GasAndWaterVo;
import com.bluezone.dec.utils.RestUtils;
import com.c503.sc.utils.basetools.C503PropertiesUtils;

import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author HHL
 * @description 监控预警服务层接口实现类
 * @date 2018/11/12 - 14:36
 */
@Service
public class MonitorAlarmServiceImpl implements MonitorAlarmService {

    private static Logger log = LoggerFactory.getLogger(MonitorAlarmServiceImpl.class);

    @Autowired
    private AppConfig appConfig;

    @Autowired
    private RestUtils restUtils;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取环境监控预警情况
     *
     * @return
     */
    @Override
    public int getEnvironmentMonitorStatus() {

        if (StringUtils.isEmpty(redisTemplate.opsForValue().get(CacheConstant.ENVIRONMENTAL_MONITORING_WARNING))) {

            int i;
            int envMonitorStatusCount = 0;
            String apiUrl = "";

            try {
                apiUrl = appConfig.getDseIp() + C503PropertiesUtils.getValue(SystemConstant.API_PROPERTIES,
                        "getEnvironmentMonitorStatus");
            } catch (Exception e) {
                log.warn(CodeEnum.NO_PATH_IN_PROPERTIES.getMsg(), e);
            }

            JSONArray envMonitorStatusArray = restUtils.doGet(apiUrl);

            for (i = 0; i < envMonitorStatusArray.size(); i++) {
                envMonitorStatusCount = Integer.parseInt(envMonitorStatusArray.getJSONObject(i).get("envMonitorStatusCount").toString());
            }

            /* 设置环境监控预警情况缓存过期时间 */
            redisTemplate.opsForValue().set(CacheConstant.ENVIRONMENTAL_MONITORING_WARNING,
                    envMonitorStatusCount,
                    appConfig.getChartDataCacheTime(),
                    TimeUnit.SECONDS);

            return envMonitorStatusCount;
        } else {
            Object envMonitorStatusCount = redisTemplate.opsForValue().get(CacheConstant.ENVIRONMENTAL_MONITORING_WARNING);
            return Integer.parseInt(envMonitorStatusCount.toString());
        }

    }

    /**
     * 获取监控预警中的数据
     *
     * @return
     */
    public List<JSONObject> monitoringAndWarning(String type) {

        List<JSONObject> alarmRecordList = null;

        try {
            String apiUrl = appConfig.getDseIp() + C503PropertiesUtils.getValue(SystemConstant.API_PROPERTIES,
                    type);
            alarmRecordList = restUtils.doGet(apiUrl).toJavaList(JSONObject.class);
        } catch (Exception e) {
            log.warn(CodeEnum.NO_PATH_IN_PROPERTIES.getMsg(), e);
        }

        return alarmRecordList;
    }


    /**
     * 获取报警类型的集合
     * 预警级别的集合
     *
     * @param urlKey    指向url的key值
     * @param fieldName 所统计字段名称
     * @return
     */
    @Override
    public List<String> typeSet(String urlKey, String fieldName) {
        List<JSONObject> monitoringAndWarning = monitoringAndWarning(urlKey);
        return monitoringAndWarning.stream().filter(jsonObject -> !Strings.isNullOrEmpty(jsonObject.getString(fieldName)))
                .map(jsonObject -> jsonObject.getString(fieldName)).distinct().collect(Collectors.toList());
    }

    /***
     * 获取当年废气废水指标报警统计
     * @return
     */
    @Override
    public JSONArray getGasAndWaterAlarmStatistics() {
        JSONArray gasAndWaterCountList = null;
        try {
            String apiUrl = appConfig.getDseIp() + C503PropertiesUtils.getValue(SystemConstant.API_PROPERTIES,
                    SystemConstant.GAS_WATER_ALARM_CONUT);
            gasAndWaterCountList = restUtils.doGet(apiUrl);
        } catch (Exception e) {
            log.warn(CodeEnum.NO_PATH_IN_PROPERTIES.getMsg(), e);
        }
        return gasAndWaterCountList;
    }

    /***
     * 获取当年废气废水指标报警情况
     * @return
     */
    @Override
    public Map<String, List<GasAndWaterVo>> getGasAndWaterAlarmStatus() {
        List<GasAndWaterVo> gasAndWaterList = new ArrayList<>();
        try {
            String apiUrl = appConfig.getDseIp() + C503PropertiesUtils.getValue(SystemConstant.API_PROPERTIES,
                    SystemConstant.GAS_WATER_ALARM_STATUS);
            gasAndWaterList = restUtils.doGet(apiUrl).toJavaList(GasAndWaterVo.class);
        } catch (Exception e) {
            log.warn(CodeEnum.NO_PATH_IN_PROPERTIES.getMsg(), e);
        }
        Map<String, List<GasAndWaterVo>> resultMap;
        resultMap = gasAndWaterList
                .stream()
                .collect(Collectors.groupingBy(GasAndWaterVo::getCode));
        return resultMap;
    }

}
